package com.xyh.flowershop.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyh.flowershop.context.WebContext;
import com.xyh.flowershop.domain.Comment;
import com.xyh.flowershop.mapper.CommentMapper;
import com.xyh.flowershop.service.CommentService;
import com.xyh.flowershop.vo.req.comment.CommentPageReqVo;
import com.xyh.flowershop.vo.req.comment.CommentReqVo;
import com.xyh.flowershop.vo.resp.comment.CommentRespPageVo;
import com.xyh.flowershop.vo.resp.comment.CommentRespVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author 小约翰可汗
 * @className CommentServiceImpl
 * @createTime 2024/5/3020:07
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Override
    public String publishComment(CommentReqVo vo) {
        Comment comment = new Comment();
        BeanUtils.copyProperties(vo, comment);
        comment.setUserId(WebContext.get());
        comment.setCreateTime(new Date());
        this.save(comment);
        return comment.getId();
    }

    @Override
    public Boolean checkIsBuyer(String id) {
        // 校验是否购买商品

        return baseMapper.checkIsBuyer(id, WebContext.get()) > 0;
    }

    public IPage<CommentRespPageVo> findCommentByPage(CommentPageReqVo vo){
        IPage<CommentRespPageVo> page = new Page<>(vo.getPageIndex(),vo.getPageSize());
        page = baseMapper.findCommentByPage(page,vo);
        List<CommentRespPageVo> records = page.getRecords();
        if(!page.getRecords().isEmpty()){
            page.setRecords(findSubComments(records));
        }
        return page;
    }

    private List<CommentRespPageVo> findSubComments(List<CommentRespPageVo> parentComments){
        List<String> parentIds = parentComments.stream().map(CommentRespPageVo::getId).collect(Collectors.toList());
        List<CommentRespVo> subComments = baseMapper.findSubComments(parentIds);
        // 构建子评论的map
        Map<String, List<CommentRespVo>> subCommentsMap = subComments.stream().collect(
                Collectors.groupingBy(CommentRespVo::getParentId));
        // 遍历父评论，将子评论添加到父评论的子评论列表中
        for(CommentRespPageVo parentComment : parentComments){
            String parentId = parentComment.getId();
            List<CommentRespVo> subCommentList = subCommentsMap.get(parentId);
            if(Objects.nonNull(subCommentList)) {
                parentComment.setSubComments(subCommentList);
            }
        }
        return parentComments;
    }
}
